<?php

namespace Yjius\common;

class ZipHelper
{
    /**
     * Purpose: 打包本地文件到压缩包
     * Author:yingjiusheng@gsdata.cn
     * @date 2022/7/7 14:13
     * $fileList 本地文件列表
     * $zipFileName 压缩包名称
     * $zipArchive 压缩包对象
     */
    public static function zipFiles($fileList = [], $zipFileName = '', $zipArchive = '')
    {
        if (empty($zipFileName) || empty($fileList)) {
            throw new \Exception("传入参数不正确");
        }
        $fileinfo = pathinfo($zipFileName);
        if (empty($fileinfo) || $fileinfo['extension'] != 'zip') {
            throw new \Exception("压缩包文件必须是.zip格式");
        }
        try {
            $zipArchiveType = empty($zipArchive) ? \ZipArchive::CREATE : $zipArchive;
            $zip = new \ZipArchive();
            $zip->open($zipFileName, $zipArchiveType);   //打开压缩包
            foreach ($fileList as $file) {
                $zip->addFile($file, basename($file));   //向压缩包中添加文件
            }
            $rs = $zip->close();  //关闭压缩包
            return $zipFileName;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

}
